// pages/payment-success/payment-success.js
Page({
  data: {
    patientInfo: {
      name: '',
      relation: '本人',
      idNumber: '',
      patientId: null
    },
    showPatientModal: false,
    patientList: [],
    paymentData: {
      feeType: '西药费',
      department: '消化内科',
      doctor: '李梅',
      patient: '牛韦',
      cardNumber: '610*********0989',
      paymentMethod: '余额',
      cardBalance: '1400.00',
      totalAmount: '600.00',
      orderNumber: '202010090900001',
      orderTime: '2020/10/09 09:00:00',
      feeDetails: [
        {
          id: 1,
          name: '普罗布考片',
          unitPrice: '50.00',
          quantity: 3,
          total: '150.00'
        },
        {
          id: 2,
          name: '阿司匹林肠溶片',
          unitPrice: '50.00',
          quantity: 3,
          total: '150.00'
        }
      ]
    }
  },

  onLoad(options) {
    console.log('缴费成功页面加载，参数:', options);
    
    // 加载当前就诊人信息
    this.loadCurrentPatient();
    
    // 从页面参数获取缴费信息
    if (options.feeType) {
      this.setData({
        'paymentData.feeType': decodeURIComponent(options.feeType)
      });
    }
    if (options.department) {
      this.setData({
        'paymentData.department': decodeURIComponent(options.department)
      });
    }
    if (options.doctor) {
      this.setData({
        'paymentData.doctor': decodeURIComponent(options.doctor)
      });
    }
    if (options.patient) {
      this.setData({
        'paymentData.patient': decodeURIComponent(options.patient)
      });
    }
    if (options.amount) {
      this.setData({
        'paymentData.totalAmount': options.amount
      });
    }
    if (options.dateTime) {
      this.setData({
        'paymentData.orderTime': decodeURIComponent(options.dateTime)
      });
    }

    // 如果有缴费ID，从服务器加载详细信息
    if (options.id) {
      this.loadPaymentDetail(options.id);
    }
  },

  // 加载当前患者信息
  loadCurrentPatient() {
    // 从后端获取默认就诊人信息
    wx.request({
      url: 'http://localhost:8005/patient/list',
      method: 'GET',
      header: { 'Content-Type': 'application/json' },
      success: (res) => {
        if (res.statusCode === 200 && res.data) {
          let list = res.data
          if (typeof list === 'string') {
            try { list = JSON.parse(list) } catch (e) { return }
          }
          if (list.code !== undefined) list = list.data
          if (!Array.isArray(list)) return
          
          // 保存完整的就诊人列表
          const mapped = list.map(p => ({
            id: p.id,
            name: p.name,
            relation: p.relationTypeName || '本人',
            idNumber: (p.idCardNumber || '').replace(/(\w{3})\w+(\w{2})/, '$1********$2'),
            isDefault: p.isDefault === 1
          }))
          this.setData({ patientList: mapped })
          
          // 找到默认就诊人
          const defaultPatient = list.find(p => p.isDefault === 1)
          if (defaultPatient) {
            this.setData({
              patientInfo: {
                name: defaultPatient.name,
                relation: defaultPatient.relationTypeName || '本人',
                idNumber: (defaultPatient.idCardNumber || '').replace(/(\w{3})\w+(\w{2})/, '$1********$2'),
                patientId: defaultPatient.id
              }
            })
          } else {
            // 如果没有默认就诊人，使用第一个就诊人
            const firstPatient = list[0]
            if (firstPatient) {
              this.setData({
                patientInfo: {
                  name: firstPatient.name,
                  relation: firstPatient.relationTypeName || '本人',
                  idNumber: (firstPatient.idCardNumber || '').replace(/(\w{3})\w+(\w{2})/, '$1********$2'),
                  patientId: firstPatient.id
                }
              })
            }
          }
        }
      }
    })
  },

  // 切换就诊人
  switchPatient() {
    // 先加载患者列表
    this.loadPatientList()
  },
  
  // 加载患者列表
  loadPatientList() {
    wx.showLoading({ title: '加载中...' })
    wx.request({
      url: 'http://localhost:8005/patient/list',
      method: 'GET',
      header: { 'Content-Type': 'application/json' },
      success: (res) => {
        wx.hideLoading()
        if (res.statusCode === 200 && res.data) {
          let patientData = res.data
          
          // 处理数据格式
          if (typeof patientData === 'string') {
            try {
              patientData = JSON.parse(patientData)
            } catch (e) {
              console.error('JSON解析失败:', e)
              return
            }
          }
          
          // 处理Result包装的数据
          if (patientData.code !== undefined) {
            if (patientData.code !== 200) {
              console.error('后端返回错误:', patientData.message)
              wx.showToast({
                title: patientData.message || '请求失败',
                icon: 'none'
              })
              return
            }
            patientData = patientData.data
          }
          
          // 提取患者数组
          if (!Array.isArray(patientData)) {
            if (patientData.data && Array.isArray(patientData.data)) {
              patientData = patientData.data
            } else if (patientData.list && Array.isArray(patientData.list)) {
              patientData = patientData.list
            } else if (patientData.patients && Array.isArray(patientData.patients)) {
              patientData = patientData.patients
            } else {
              console.error('数据不是数组格式:', patientData)
              return
            }
          }
          
          // 构建选择列表
          const itemList = patientData.map(patient => 
            `${patient.name || patient.patientName} (${patient.relationTypeName || patient.relationship || '本人'})`
          )
          
          wx.showActionSheet({
            itemList: itemList,
            success: (res) => {
              if (res.tapIndex >= 0 && res.tapIndex < patientData.length) {
                const selectedPatient = patientData[res.tapIndex]
                const patientInfo = {
                  name: selectedPatient.name || selectedPatient.patientName,
                  relation: selectedPatient.relationTypeName || selectedPatient.relationship || '本人',
                  idNumber: selectedPatient.idCardNumber || selectedPatient.idCard || '622*********0909',
                  patientId: selectedPatient.id || selectedPatient.patientId
                }
                
                this.setData({
                  patientInfo: patientInfo
                })
                
                // 可选：缓存 patientId，便于后续页面使用
                const cacheUser = wx.getStorageSync('userInfo') || {}
                wx.setStorageSync('userInfo', { ...cacheUser, patientId: patientInfo.patientId })
                
                wx.showToast({
                  title: '已切换到' + patientInfo.name,
                  icon: 'success'
                })
              }
            }
          })
        } else {
          wx.showToast({
            title: '加载患者列表失败',
            icon: 'none'
          })
        }
      },
      fail: (error) => {
        wx.hideLoading()
        console.error('网络请求失败:', error)
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        })
      }
    })
  },

  // 关闭就诊人模态框
  closePatientModal() {
    this.setData({
      showPatientModal: false
    });
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 阻止事件冒泡
  },

  // 加载缴费详情
  loadPaymentDetail(paymentId) {
    wx.showLoading({
      title: '加载中...'
    });

    wx.request({
      url: `http://localhost:8080/payment/detail/${paymentId}`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      },
      success: (res) => {
        wx.hideLoading();

        if (res.statusCode === 200 && res.data) {
          let paymentData = res.data;

          // 处理数据格式
          if (typeof paymentData === 'string') {
            try {
              paymentData = JSON.parse(paymentData);
            } catch (e) {
              console.error('JSON解析失败:', e);
              return;
            }
          }

          // 处理Result包装的数据
          if (paymentData.code !== undefined) {
            if (paymentData.code !== 200) {
              console.error('后端返回错误:', paymentData.message);
              return;
            }
            paymentData = paymentData.data;
          }

          // 更新页面数据
          if (paymentData) {
            this.setData({
              paymentData: {
                ...this.data.paymentData,
                ...paymentData
              }
            });
          }
        }
      },
      fail: (error) => {
        wx.hideLoading();
        console.error('加载缴费详情失败:', error);
      }
    });
  },

  // 查看缴费详情
  viewPaymentDetails() {
    wx.navigateTo({
      url: `/pages/payment-details/payment-details?paymentInfo=${JSON.stringify(this.data.paymentData)}`
    });
  },

  // 返回首页
  returnToHome() {
    wx.navigateBack({
      delta: 3 // 返回到首页，跳过确认缴费和待缴费页面
    });
  }
});
